package com.wt.loadbalance;

import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.cluster.LoadBalance;

import java.util.List;

/**
 * @Auther: wtt
 * @Date: 2022/1/15 17:43
 * @Description:
 */
public class OnlyFirstLoadbalancer implements LoadBalance {

    @Override
    public <T> Invoker<T> select(List<Invoker<T>> list, URL url, Invocation invocation) throws RpcException {
        //所有服务提供者按照字母排序 + 端口排序
        Invoker<T> tInvoker = list.stream().sorted((o1, o2) -> {
            final int ipCompare = o1.getUrl().getIp().compareTo(o2.getUrl().getIp());
            if (ipCompare == 0) {
                return Integer.compare(o1.getUrl().getPort(), o2.getUrl().getPort());
            }
            return ipCompare;
        }).findFirst().get();
        System.out.println("自定义的负载均衡策略：" + tInvoker.getUrl());
        return tInvoker;
    }
}
